// pages/sendCoupon/sendCoupon.js
const app = getApp();
const req = require("../../utils/http.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    send_coupon_params:[],

  },


  getcoupon: function (params) {
    // 插件返回信息在params.detail
    let t = this
    let { coupon_code, out_request_no, stock_id } = params.detail.send_coupon_result[0]
    let outTradeNo = t.data.outTradeNo
    let memberCoupon = { couponCode: coupon_code, outRequestNo: out_request_no, stockId: stock_id, outTradeNo}  
    console.log('memberCoupon', memberCoupon)
    if (params.detail.errcode=='OK'){
      t.saveMemberCoupon(memberCoupon)
    
    }else{
      wx.showToast({
        title: '！',
        icon: 'none',
        duration: 800
      })
    }
  },

 //保存商家到会员列表
  // POST /coupon/wxUser / saveMemberCoupon
  saveMemberCoupon(params){
    req.wxReq("/coupon/wxUser/saveMemberCoupon","POST",params).then(res=>{
      console.log('会员列表',res)
      if(res.data.code==200){
        wx.showToast({
          title: '发券成功，请往微信卡包里查看！',
          icon: 'none',
          duration: 800
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '../index/index',
          })
        }, 1000)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let value = options.value
    let outTradeNo = options.outTradeNo
    req.wxReq('/coupon/wxUser/doSign/' + value, "GET").then(res => {
      console.log(res)
      if (res.data.code == 200) {
        this.setData({
          send_coupon_params: res.data.result.send_coupon_params,
          sign: res.data.result.sign,
          send_coupon_merchant: res.data.result.send_coupon_merchant,
          outTradeNo,
        })
        this.getcoupon();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})